#pragma once
#include "udp_socket.hpp"
#include <functional>

typedef std::function<void(const std::string &, std::string *)> Handler;

class UdpServer
{
public:
    UdpServer()
    {
        assert(sock_.Socket());
    }
    ~UdpServer()
    {
        sock_.Close();
    }
    bool Start(Handler handler)
    {
        bool ret = sock_.Bind();
        if (!ret)
        {
            return false;
        }
        while (1)
        {
            std::string req;
            std::string remote_ip;
            uint16_t remote_port;
            bool ret = sock_.RecvFrom(&req, &remote_ip, &remote_port);
            if (!ret)
            {
                continue;
            }
            std::string resp;
            handler(req, &resp);

            sock_.SendTo(resp, remote_ip, remote_port);
            printf("we server have done this handler , the result is %s,[ip:%s][port:%d]\n", resp.c_str(), remote_ip.c_str(), remote_port);
        }
        sock_.Close();
        return true;
    }

private:
    UdpSocket sock_;
};